package com.py.chat.server.businese;

import com.py.chat.bean.Gloable;
import com.py.chat.bean.User;
import com.py.chat.dao.UserDao;
import com.py.chat.proto.IBusineseHandle;
import com.py.chat.server.ChatServer;
import com.py.chat.service.UserService;
import com.google.protobuf.MessageLite;
import com.py.chat.proto.ChatProbuf.CTSLogin;
import com.py.chat.proto.ChatProbuf.CTSRegist;
import com.py.chat.proto.ChatProbuf.STCChatRet;
import com.py.chat.proto.ChatProbuf.STCLoginRet;

public class ServerLoginHandle extends IBusineseHandle<CTSLogin>  {

	@Override
	public MessageLite handle(CTSLogin msg) {
		
		String name = msg.getName();
		String password = msg.getPwd();
		STCLoginRet.Builder builder = STCLoginRet.newBuilder();  //status  0失败 1成功 
		// 判断是否登陆
		if (session.user != null && name.equals(session.user.getName())) {
			return builder.setStatus(0).setMsg("该用户已登陆").build();
		}
		
		// 判断用户名密码不能为空
		if (name == "" && password == "") {
			builder.setMsg("登陆失败，用户名或密码不能为空").setStatus(0);
			return builder.build();
		}
		// 判断用户名和密码是否正确
		User resultUser = UserService.checkUser(name, password);
		if(resultUser != null){
			builder.setMsg("登陆成功").setStatus(1);
			if(resultUser.getSession() == null){
				resultUser.setSession(session);
				//TODO 检查逻辑
				session.setUser(resultUser);
			}
			Gloable.userMap.put(resultUser.getId(), resultUser);
			Gloable.sessionMap.put(resultUser.getId(), resultUser);
			ChatServer.broadcast(STCChatRet.newBuilder().setStatus(0).setMsg(name+"上线了").build(),resultUser);
		}else{
			builder.setMsg("登陆失败").setStatus(0);
		}
		return builder.build();
	}
}
